<?php

namespace G4T\Util;


use \Doctrine\Common\Cache\ArrayCache;
use \Doctrine\Common\Annotations\AnnotationRegistry;
use \Doctrine\Common\Annotations\SimpleAnnotationReader;

class MetadataItem
{
    private static $types = array('image', 'email', 'file', 'manytoone');

    protected $params;

    const ANNOTATION_NAMESPACE = 'G4T\Util\Annotation';

    public function __construct(\ReflectionProperty $property)
    {
        AnnotationRegistry::registerFile('Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
        AnnotationRegistry::registerFile('G4T/Util/Annotation/Annotations.php');

        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        $reader = new \Doctrine\Common\Annotations\CachedReader($reader, new ArrayCache());

        $annotations = $reader->getPropertyAnnotations($property);

        foreach ($annotations as $annotation) {
            $class = preg_replace('/.*\\\/', '', get_class($annotation));
            $this->params[strtolower($class)] = (array) $annotation;
        }
    }

    public function isRequired()
    {
        return isset($this->params['column']['nullable']) ? !$this->params['column']['nullable'] : false;
    }

    public function getType()
    {
        foreach (self::$types as $type) {
            if (isset($this->params[$type])) {
                return $type;
            }
        }

        return $this->params['column']['type'];
    }

    public function getTitle()
    {
        return isset($this->params['column']) ? $this->params['column']['name'] : 'No label';
    }

    public function getParam()
    {
        return isset($this->params[$this->getType()]) ? $this->params[$this->getType()] : $this->params['column'];
    }
}
